package cn.wolfcode.luowowo.web.persistence;

import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.key.RedisKeys;
import cn.wolfcode.luowowo.redis.redisService.IStrategyStatisVoService;
import cn.wolfcode.luowowo.util.DBHelper;
import cn.wolfcode.luowowo.vo.FavorStrategyVO;
import cn.wolfcode.luowowo.vo.StrategyStatisVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//@Component
public class RedisDataPersistenceJob {

    @Autowired
    private IStrategyStatisVoService strategyStatisVoService;
    @Autowired
    private MongoTemplate mongoTemplate;

    // @Scheduled是定时任务标签
    // cron 指定任务时间间隔: 没有标准,有redis数据量决定,如果数据量较大,时间周期适当缩短
    @Scheduled(cron = "0/20 * * * * ? ")
    public void doWorkForStrategyStatisVo() {
        System.out.println("-------------------VO持久化 - start------------------");

        //一.从缓存中获取所有的vo数据
        //1.先拼接所有vo的key
        String pattern = RedisKeys.STRATEGY_STATIS_VO.join("*");
        //2.获取所有vo对象
        List<StrategyStatisVO> vos = strategyStatisVoService.listStrategyVoByPattern(pattern);

        //二.更新vo数据到mongodb数据库
        for (StrategyStatisVO vo : vos) {
            //根据vo中的攻略id 更新对应攻略的统计数据
            strategyStatisVoService.updateStrategyVo(vo);
        }

        System.out.println("-------------------VO持久化 - end------------------");
    }

    //把用户的攻略收藏数据(FavorStrategyVO) 进行持久化
    @Scheduled(cron = "0/20 * * * * ? ")
    public void doWorkForStarategyFavor() {
        //一.从缓存中获取所有的vo数据

        // 1.先拼接所有vo的key
        String pattern = RedisKeys.USER_STRATEGY_FAVOR.join("*");
        // 2.获取缓存中 所有用户 的收藏攻略的缓存对象
        ArrayList<FavorStrategyVO> favorStrategyVOs = strategyStatisVoService.listStrategFavorByPattern(pattern);

        //二.更新vo数据到mongodb数据库

        //1.遍历每一个FavorStrategyVO对象
        for (FavorStrategyVO favorStrategyVO : favorStrategyVOs) {
            if (favorStrategyVO != null) {
                //获取对象中的用户id
                String userInfoId = favorStrategyVO.getUserInfoId();
                //获取对象中的收藏攻略id集合
                List<String> favorStrategyIds = favorStrategyVO.getFavorStrategyIds();

                //把收藏攻略id持久化到mongodb数据库
                Query query = new Query();
                query.addCriteria(Criteria.where("_id").is(userInfoId));
                UserInfo userInfo = new UserInfo();
                userInfo.setFavors(favorStrategyIds);
                DBHelper.update(mongoTemplate, query,userInfo,"favors");
            }
        }
    }
}
